package wikitools.servlet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wikitools.model.TextBase;
import wikitools.model.Article;
import wikitools.util.XMLUtil;

/**
 * Servlet implementation class GetArticleList
 */
public class GetArticleList extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetArticleList() {
        super();

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        serveArticleListAsFeed(request, response);

    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @SuppressWarnings("unused")
    private void serveArticleList(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        String contextPath = this.getServletContext().getRealPath(
                request.getContextPath());
        // ServletUtil.alert(contextPath+"haa", response);
        List<Article> list = new TextBase().getArticleList();

        ServletUtil.writeXML(XMLUtil.toXML(list), response);
    }

    private void serveArticleListAsFeed(HttpServletRequest request,
            HttpServletResponse response) throws MalformedURLException,
            IOException {

        response.setContentType("text/xml");
        List<Article> list = new TextBase().getArticleList();

        //TODO: use StringBuilder to do the replacement in a faster way.
        String ret = XMLUtil.toXML(list);
        System.out.println(ret);
        ret = ret.replaceAll("<list>", "<channel>");
        ret = ret.replaceAll("</list>", "</channel>");
        ret = ret.replaceAll("<article>", "<item>");
        ret = ret.replaceAll("</article>", "</item>");
        ret = ret.replaceAll("<myarticle>", "<item>");
        ret = ret.replaceAll("</myarticle>", "</item>");
        

        ServletUtil.write(ret, response);

        System.out.println("Serving the feed...");

    }



}
